<template>
  <FIModel v-model="visible" title="分段设置" @close="closeClick">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :showCollapse="false"
      @submit="getPostList(state.query.seqTypeId)"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="seqTypeId" label="序列号编码">
          <FIInput v-model="state.query.seqTypeId" clearable />
        </FIFormItem>
      </el-col>
      <!-- <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem name="codesetCode" label="代码分类编码">
            <FIInput v-model="state.query.codesetCode" clearable />
          </FIFormItem>
        </el-col> -->
    </FISearchForm>
    <div class="margin-bottom20"></div>

    <FITable
      ref="tableRef"
      class="box-radius2"
      title="序列号分段列表"
      :id="`result_${tableId}`"
      :showSaveModel="false"
      :readonly="false"
      :data="dataList"
      primaryKey="subsecId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      delete-id="deleteSubsec"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="getPostList(state.query.seqTypeId)"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleAction"
      :settingConfig="settingConfig"
      @row-add="rowAdd"
      @row-delete="deleteRow"
    >
      <!-- <template #subsecType="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.subsecType"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.subsecType }}</span>
      </template> -->
      <template #dateFormat="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.dateFormat"
          valueCustom="value"
          :options="dateArr"
          clearable
        />
        <span v-else>{{ valueToLabel(scope.row.dateFormat, dateArr) }}</span>
      </template>
      <template #headerBtn>
        <FIButton id="openTest" border @click="xlNoClick"></FIButton>
        <FIButton id="saveSubsec" border @click="addRowSave"></FIButton>

        <!-- <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'deleteSubsec', border: true }"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn> -->
      </template>
    </FITable>

    <registerForm
      :modelValue="modelValue"
      @update:modelValue="(newValue) => (modelValue = newValue)"
      :formData="state.query"
    ></registerForm>
    <!-- <linkForm :linkShow="linkShow" @update:linkShow="(newValue) => (linkShow = newValue)" :linkData="selectedlink"></linkForm> -->
    <template #footer>
      <slot name="footer">
        <div class="dialog-footer">
          <FIButton @click="closeClick" border>关闭</FIButton>
        </div>
      </slot>
    </template>
  </FIModel>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, toRaw } from 'vue'
import { apiGetCodeitems } from '@/api/configEnvMaint/index'
import FIFormItem from '@/components/FIFormItem.vue'
import registerForm from './register.vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FITable from '@/components/FITable/index.vue'
import FIInput from '@/components/FIInput.vue'
import FIForm from '@/components/FIForm.vue'
import FIModel from '@/components/FIModel.vue'
import { valueToLabel } from '@/utils/common.js'

// import { apiRegist,apiQueryUserPostsWithDept} from '@/api/user'
import {
  apiGgetsequenceMaint,
  apideleteSubsecsequenceMaint,
  apisaveSubsecsequenceMaint,
} from '@/api/configEnvMaint/index.ts'
import { apiQueryCodeitem } from '@/api/common'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
const emits = defineEmits(['close', 'update:postShow', 'get-list'])
const props = defineProps({
  // 圆角大小
  postShow: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const dateArr = ref([
  {
    label: 'YY',
    value: 'yy',
  },
  {
    label: 'YYMM',
    value: 'yyMM',
  },
  {
    label: 'YYYY',
    value: 'yyyy',
  },
  {
    label: 'YYMMDD',
    value: 'yyMMdd',
  },
  {
    label: 'YYYYMM',
    value: 'yyyyMM',
  },
  {
    label: 'YYYYMMDD',
    value: 'yyyyMMdd',
  },
])
const linkShow = ref(false)
const tableRef = ref(null)
const modelValue = ref(false)
const selectedlink = ref({})
const state = reactive({
  query: {
    seqTypeId: '',
    // codesetCode:'',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const searchWrapperSpan = 8
const register = reactive({
  codesetCode: '',
  userName: '',
  password: '',
  loginName: '',
  mobile: '',
  gender: '',
  email: '',
  businessPhone: '',
  jobNo: '',
  deptId: '',
})
const arr2 = ref([])
const dataList = ref([])
const getPostList = (seqTypeId) => {
  if (!state.query.seqTypeId) {
    useMessage().warning('请输入序列号编码')
    return
  }
  const par = {
    seqTypeId: seqTypeId,
    current: 1,
    size: 999,
  }
  apiGgetsequenceMaint(par)
    .then((res) => {
      if (res.data.success) {
        // pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.length)
        if (res.data.data.length > 0) {
          dataList.value = res.data.data.map((item) => ({
            ...item,
            seqTypeId: seqTypeId,
          }))
        } else {
          // 如果数组为空，创建一个包含seqTypeId的新对象
          dataList.value = [
            // {
            //   seqTypeId: seqTypeId,
            // },
          ]
        }
        //         dataList.value = res.data.data.map(item => ({
        //   ...item,
        //   seqTypeId:seqTypeId , // 这里替换为你要添加的值
        // }));
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  // searchFn()
  getPostList(state.query.seqTypeId)
}
const rowAdd = () => {
  console.log(checkedRows.value, 'checkedRows.value')
  tableRef.value.setCellValue(dataList.value.length, 'seqTypeId', state.query.seqTypeId)
  for (let i of checkedRows.value) {
    i.seqTypeId = state.query.seqTypeId
  }
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  // searchFn()
  getPostList(state.query.seqTypeId)
}
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.subsecId) ids.push(item?.subsecId)
    })
  isTableLoading.value = true
  apideleteSubsecsequenceMaint(ids)
    .then((res) => {
      isTableLoading.value = false
      // searchFn()
      getPostList(state.query.seqTypeId)
      emits('get-list')
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const isTableLoading = ref(false)
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 页面编码
const tableId = 'pageMaint'
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100],
})
const columns: Column[] = reactive([
  // {
  //   label: '分段ID',
  //   prop: 'subsecId',
  //   align: 'center',
  //   width: '180',
  //   // editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '序列号编码',
    prop: 'seqTypeId',
    align: 'center',
    width: '180',
    queryName: '',
    editable: true,
    // sortable: true,
    // filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { seqTypeId: [{ required: true }] },
    },
  },
  {
    label: '分段序号',
    prop: 'subsecSeq',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '180',
    editType: 'input',
    editable: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    // modelValue: { inputValue: '', isBlank: false, notBlank: false },
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { subsecSeq: [{ required: true, message: '请输入页面名称', trigger: 'blur' }] },
    },
  },
  {
    label: '分段名称',
    prop: 'subsecName',
    align: 'center',
    width: '180',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editable: true,
    // filterable: true,
    modelValue: { inputValue: '' },
    // sortable: true,
    sortValue: '',
    // editConfig: {
    //   rules: { remark: [{ required: false, message: '请输入备注', trigger: 'blur' }] },
    // },
  },

  {
    label: '分段类型',
    prop: 'subsecType',
    align: 'center',
    width: '180',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    // configValueToLable: {
    //   list: [
    //     { value: '1', label: '是' },
    //     { value: '0', label: '否' },
    //   ],
    // },
    editConfig: {
      rules: { subsecType: [{ required: true, message: '请输入分段类型', trigger: 'blur' }] },
      options: [],
      // codeOption:{ codesetCode:'iplat.ed.secType'},
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '分段长度',
    prop: 'subsecLen',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { subsecLen: [{ required: true, message: '请输入所属项目', trigger: 'blur' }] },
    },
  },
  {
    label: '定义内容',
    prop: 'subsecContent',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    //   editConfig: {
    //     rules: { projectName: [{ required: true, message: '请输入所属项目', trigger: 'blur' }] },
    //   },
  },
  {
    label: '日期格式',
    prop: 'dateFormat',
    align: 'center',
    width: '180',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    //   editConfig: {
    //     rules: { projectName: [{ required: true, message: '请输入所属项目', trigger: 'blur' }] },
    //   },
  },
  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  //   {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [
  //     // { id: 'delete', type: 'delete' },
  //     // { id: 'b5555', type: 'add' },
  //     { id: 'openTest', type: 'openTest' },
  //   ],
  // },
])
const dataArr = ref([])
const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
let visible: any = computed({
  get() {
    return props.postShow
  },
  set(val) {
    emits('update:postShow', val)
  },
})
const selectedform = ref({})
const handleAction = (item, rowData, butoninfo) => {
  console.log(item, rowData, butoninfo)
  // isVisible.value=true
  selectedform.value = rowData
  // linkShow.value = true
  selectedlink.value = rowData

  modelValue.value = true
}
const xlNoClick = () => {
  modelValue.value = true
}

const addRowSave = () => {
  handleSave()
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  //  const data=checkedRows.value.map(item => ({
  //   ...item,
  //   seqTypeId: state.query.seqTypeId, // 这里替换为你要添加的值
  // }));
  apisaveSubsecsequenceMaint(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        getPostList(props.editData.seqTypeId)
        useMessage().success(res.data.message)
        tableRef.value.clearSelection()
        emits('get-list')
        // searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const smallCode = () => {
  apiGetCodeitems({ codesetCode: 'iplat.ed.secType' })
    .then((res) => {
      console.log(res, '小代码')
      if (res.data.success) {
        dataArr.value = res.data.data.map((v) => {
          return {
            label: v.itemCname,
            value: v.itemCode,
          }
        })
        tableRef.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'subsecType') {
            v.editConfig.options = dataArr
          }
        })
      }
    })
    .catch((error: any) => {})
}
const closeClick = () => {
  emits('update:postShow', false)
}
watch(
  () => props.postShow,
  (newValue) => {
    smallCode()
    if (props.editData.seqTypeId) {
      state.query.seqTypeId = props.editData.seqTypeId
      getPostList(props.editData.seqTypeId)
    }
  }
)

const getProjectname = () => {
  apiQueryCodeitem({ codesetCode: 'iplat.ed.secType' }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data.result) &&
        res.data.data.result.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.itemCode}] ${item.itemCname}`
          item.value = item.itemCode
        })
      if (Array.isArray(res.data.data.result)) {
        const newArray = res.data.data.result.map((item) => ({
          label: `[${item.itemCode}] ${item.itemCname}`,
          value: item.itemCode,
        }))
        arr2.value = newArray
      }
    }
  })
}
onMounted(() => {
  getProjectname()
})
</script>
<style lang="less" scoped></style>
